/**
 * 1.先获取部门信息和职位信息并绑定到下拉框中
 * 2.获取用户输入数据并验证，然后发送至服务器
 *
 */

let useraddModel = (function () {
  let $username = $(".username"),
    $spanusername = $(".spanusername"),
    $man = $("#man"),
    $woman = $('#woman'),
    $useremail = $('.useremail'),
    $spanuseremail = $(".spanuseremail"),
    $userphone = $(".userphone"),
    $spanuserphone = $(".spanuserphone"),
    $userdepartment = $(".userdepartment"),
    $userjob = $(".userjob"),
    $userdesc = $(".userdesc"),
    $submit = $(".submit");

  let userId = null;

  // 绑定部门信息和职位信息
  async function bandDepartAndJob() {
    let departmentInfo = null,
      jobInfo = null,
      isStorage = false;

    // 直接走封装好的方法
    departmentInfo = await queryDepart();
    jobInfo = await queryJob();
    // console.log(departmentInfo, jobInfo);

    // 生成DOM结构并渲染
    if (departmentInfo.code === 0) {
      departmentInfo = departmentInfo.data;
      let str = ``;
      departmentInfo.forEach(item => {
        str += `<option value="${item.id}">${item.name}</option>`;
      })
      $userdepartment.html(str);
    }
    if (jobInfo.code === 0) {
      jobInfo = jobInfo.data;
      let str = ``;
      jobInfo.forEach(item => {
        str += `<option value="${item.id}">${item.name}</option>`;
      })
      $userjob.html(str);
    }

  }

  // 表单校验：用户名|邮箱|电话
  function checkUserName() {
    let val = $username.val().trim();
    if (val.length === 0) {
      $spanusername.html("用户名不能为空！");
      return false;
    }
    if (!/^[\u4E00-\u9FA5]{2,10}(·[\u4E00-\u9FA5]{2,10}){0,2}$/.test(val)) {
      $spanusername.html("用户名为2-10位汉字！");
      return false;
    }
    $spanusername.html("");
    return true;
  }
  function checkEmail() {
    let val = $useremail.val().trim();
    if (val.length === 0) {
      $spanuseremail.html("邮箱不能为空！");
      return false;
    }
    if (!/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(val)) {
      $spanuseremail.html("邮箱格式错误！");
      return false;
    }
    $spanuseremail.html("");
    return true;
  }
  function checkPhone() {
    let val = $userphone.val().trim();
    if (val.length === 0) {
      $spanuserphone.html("手机号码不能为空！");
      return false;
    }
    if (!/^1[34578]\d{9}$/.test(val)) {
      $spanuserphone.html("手机号码格式错误！");
      return false;
    }
    $spanuserphone.html("");
    return true;
  }

  // 处理点击提交按钮
  async function handleSubmit() {
    console.log('点击了....')
    // 表单数据的二次校验
    if (!checkUserName() || !checkEmail() || !checkPhone()) return;

    // 获取用户输入的信息
    // name=xxx&sex=0&email=xxx&phone=xxx&departmentId=1&jobId=1&desc=xxx
    let params = {
      name: $username.val().trim(),
      sex: $man.prop('checked') ? 0 : 1,
      email: $useremail.val().trim(),
      phone: $userphone.val().trim(),
      departmentId: $userdepartment.val(),
      jobId: $userjob.val(),
      desc: $userdesc.val().trim(),
    };
    // 想服务器发送请求(区分是新增还是修改)
    // console.log(userId);
    if (userId) {
      // 修改
      params.userId = userId;
      let result = await axios.post("/user/update", params)
      if (result.code == 0) {
        alert('修改成功!');
        window.location.href = '../page/userlist.html';
        return;
      }
      alert('修改失败，请重新或者联系管理员！');
      return;
    }
    // 新增
    let result = await axios.post("/user/add", params);
    if (result.code === 0) {
      alert('添加成功!');
      window.location.href = '../page/userlist.html';
      return true;
    }
    alert('添加失败，请重新或者联系管理员！');
  }

  // 向服务器请求当前id的员工数据并绑定到页面上
  async function queryBindUserInfo() {
    let result = await axios.get("/user/info", {
      params: {
        userId
      }
    });

    if (result.code == 0) {
      result = result.data;
      // console.log(result)
      // console.log(result.departmentId, result.jobId)
      $username.val(result.name);
      result.sex == 0 ? $man.prop('checked', true) : $woman.prop('checked', true);
      $useremail.val(result.email);
      $userphone.val(result.phone);
      $userdepartment.val(result.departmentId);
      $userjob.val(result.jobId);
      // $userdepartment.val(2);
      // $userjob.val(2);
      $userdesc.val(result.desc)
      return;
    }
    alert("网络出错，请重试或者联系管理员！");
    userId = null;
  }
  return {
    init() {
      bandDepartAndJob();
      // 查看是否有参数，有参数说明是编辑，无则是新增（判断当前操作是新增还是编辑）
      // queryURLParams工具类utils封装的方法
      let params = window.location.href.queryURLParams();
      if (params.hasOwnProperty("id")) {
        userId = params.id;
        // 向服务器请求当前id的员工数据并绑定到页面上
        queryBindUserInfo();
      }

      // 文本框失去焦点时进行格式校验
      $username.blur(checkUserName);
      $useremail.blur(checkEmail);
      $userphone.blur(checkPhone);

      // 点击提交按钮
      $submit.click(handleSubmit);
    }
  }
})();

useraddModel.init();





